<template>
  <section>
    <Form :model="formItem" :label-width="90">
      <card class="card" style="margin-top:15px;">
        <p slot="title">基本信息</p>
        <div slot="extra" v-if="formItem.create_date">
            <div>入库时间: {{formItem.create_date}}</div>
        </div>
        <Row>
          <Col span="5">
            <FormItem label="姓名">
              <Input :disabled="isDisabled" v-model="formItem.name" style="width: 180px;" placeholder="请输入姓名"
                ><Icon type="ios-person-outline" slot="prepend"></Icon>
              </Input>
            </FormItem>
          </Col>
          <Col span="4">
            <FormItem label="性别" style="margin-left:10px;">
              <Select :disabled="isDisabled" v-model="formItem.gender" placeholder="请选择性别">
                <Option value="男">男</Option>
                <Option value="女">女</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="5" style="margin-left:10px;">
            <FormItem label="身高">
              <Input
                type="number"
                number
                v-model="formItem.height"
                placeholder="请输入身高"
                style="width: 130px;" :disabled="isDisabled"
              >
                <span slot="append">cm</span>
              </Input>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="5">
            <FormItem label="出生日期">
              <DatePicker
                type="date"
                style="width: 180px;"
                placeholder="请选择出生日期"
                v-model="formItem.birthday" :disabled="isDisabled"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col span="4" style="margin-left:10px;">
            <FormItem label="现居地">
              <Cascader :disabled="isDisabled" style="width: 150px;" v-model="formItem.living_place" :render-format="format" change-on-select :data="regionList" placeholder="请选择现居地"></Cascader>
            </FormItem>
          </Col>
          <Col span="5" style="margin-left:10px;">
            <FormItem label="家乡">
              <Cascader :disabled="isDisabled" style="width: 150px;" v-model="formItem.hometown" :render-format="format" change-on-select :data="regionList" placeholder="请选择家乡"></Cascader>
            </FormItem>
          </Col>
        </Row>
      </card>
      <card class="card" style="margin-top:15px;">
        <p slot="title">照片</p>
        <div slot="extra">
          <Button type="primary" size="small" @click="downPictures">下载照片</Button>
        </div>
        <Row style="margin-top: 15px">
          <Col span="12">
            <FormItem label="封面:">
              <div
                class="demo-upload-list"
                v-if="formItem.cover_img"
              >
                <template>
                  <img :src="formItem.cover_img" />
                  <div class="demo-upload-list-cover">
                    <Icon
                      type="ios-trash-outline"
                      @click.native="handleCoverRemove()"
                    ></Icon>
                  </div>
                </template>
              </div>
              <Upload
                ref="uploadCover"
                v-if="!formItem.cover_img"
                :show-upload-list="false"
                :before-upload="handleCoverBeforeUpload"
                :format="['jpg', 'jpeg', 'png']"
                :max-size="2048"
                type="drag"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                action="image/upload" :disabled="isDisabled"
                style="display: inline-block; width: 200px;"
              >
                <div style="width: 200px; height: 100px; line-height: 100px">
                  <Icon type="md-add" size="20"></Icon>
                </div>
              </Upload>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="文中图:">
              <template v-for="(item, index) in formItem.img_list">
                <div
                  :key="index"
                  class="demo-upload-list"
                  v-if="item"
                >
                  <img :src="item" />
                  <div class="demo-upload-list-cover">
                    <Icon
                      type="ios-trash-outline"
                      @click.native="handleRemove(index)"
                    ></Icon>
                  </div>
                </div>
              </template>
              <Upload
                ref="upload"
                v-if="formItem.img_list.length < 3"
                :show-upload-list="false"
                :before-upload="handleImgBeforeUpload"
                :format="['jpg', 'jpeg', 'png']"
                :max-size="2048"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                type="drag"
                action="image/upload"
                style="display: inline-block; width: 200px;" :disabled="isDisabled"
              >
                <div style="width: 200px; height: 100px; line-height: 100px">
                  <Icon type="md-add" size="20"></Icon>
                </div>
              </Upload>
            </FormItem>
          </Col>
        </Row>
      </card>
      <card class="card" style="margin-top:15px;">
      <p slot="title">学历工作信息</p>
      <Row style="margin-top: 15px">
        <Col span="5">
          <FormItem label="学历">
            <Select :disabled="isDisabled" v-model="formItem.education" style="width: 120px;"  placeholder="请选择学历">
              <Option v-for="(option, index) in educationList" :value="option.value" :key="index">{{option.label}}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="5">
          <FormItem label="毕业院校">
            <Input placeholder="请输入毕业院校" v-model="formItem.school" :disabled="isDisabled" />
            <!-- <Select :disabled="isDisabled" v-model="formItem.school"
              filterable
              placeholder="请输入毕业院校"
              :value="formItem.school"
              clearable
              :remote-method="searchSchool"
              :loading="joblLoading">
              <Option v-for="(option, index) in searchSchoolList" :value="searchSchoolList[index]" :key="index">{{searchSchoolList[index]}}</Option>
            </Select> -->
          </FormItem>
        </Col>
        <Col span="5">
          <FormItem label="职业">
            <Input placeholder="请输入职业" v-model="formItem.job" :disabled="isDisabled" />
            <!-- <Select :disabled="isDisabled" v-model="formItem.job"
              filterable
              placeholder="请输入职业"
              clearable
              :remote-method="remoteMethod"
              :loading="joblLoading">
              <Option v-for="(option, index) in searchJobList" :value="option.title" :key="index">{{option.title}}</Option>
            </Select> -->
          </FormItem>
        </Col>
      </Row>
      </card>
      <card class="card" style="margin-top:15px;margin-right: 20px;">
        <h3 class="title">自我介绍</h3>
        <Row >
          <Col span="11" v-for="num in 3" :key="num" :style="num !== 2 ? 'margin-right: 55px;' : ''">
            <FormItem
              :label="'自我介绍' + ChineseChar[num-1] + ':'"
            >
              <Input
                style="width: 100%;"
                type="textarea"
                v-model="formItem.introduce[num-1]"
                :placeholder="'请输入自我介绍' + ChineseChar[num-1]"
                :rows="5"
                :autosize="{minRows: 5,maxRows: 5}" :disabled="isDisabled"
              />
            </FormItem>
          </Col>
        </Row>
      </card>
      <Row>
        <Col span="11">
          <card class="card" style="margin-top:15px;">
            <p slot="title">理想对象</p>
            <Row>
              <Col span="24">
                <FormItem label="年龄范围:">
                  <Input
                    type="number"
                    number
                    :min="18"
                    style="width: 120px;display:inline-block;margin-right:10px;"
                    v-model="formItem.ideal_object.年龄范围[0]"
                    placeholder="最小年龄" :disabled="isDisabled"
                  /> - <Input
                    type="number"
                    number
                    style="width: 120px;display:inline-block;margin-left:10px;"
                    v-model="formItem.ideal_object.年龄范围[1]"
                    placeholder="最大年龄" :disabled="isDisabled"
                  />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="12">
                <FormItem label="外貌:">
                  <Input
                    type="textarea"
                    v-model="formItem.ideal_object.外貌"
                    placeholder="请输入理想对象外貌"
                    :rows="5"
                    :autosize="{minRows: 5,maxRows: 5}" :disabled="isDisabled"
                  />
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="性格:">
                  <Input
                    type="textarea"
                    v-model="formItem.ideal_object.性格"
                    placeholder="请输入理想对象性格"
                    :rows="5"
                    :autosize="{minRows: 5,maxRows: 5}" :disabled="isDisabled"
                  />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="12">
                <FormItem label="学历:">
                  <Select :disabled="isDisabled" v-model="formItem.ideal_object.学历" placeholder="请输入理想对象学历" style="width: 160px;">
                    <Option v-for="(option, index) in educationList" :value="option.value" :key="index">{{option.label}}</Option>
                    <Option value="不限">不限</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="坐标:">
                  <Input :disabled="isDisabled" v-model="formItem.ideal_object.坐标" placeholder="请输入坐标" />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="12">
                <FormItem label="年收入:">
                  <Input
                    type="number"
                    number
                    v-model="formItem.ideal_object.年收入"
                    placeholder="请输入年收入"
                    style="width: 160px;" :disabled="isDisabled"
                  >
                    <span slot="append">万元</span>
                  </Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="是否要有房:">
                  <RadioGroup v-model="formItem.ideal_object.是否有房">
                    <Radio label="是" :disabled="isDisabled">是</Radio>
                    <Radio label="否" :disabled="isDisabled">否</Radio>
                  </RadioGroup>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <FormItem label="补充:">
                <Input
                  type="textarea"
                  v-model="formItem.ideal_object.补充"
                  placeholder="请输入对理想对象的补充"
                  :rows="5"
                  :autosize="{minRows: 5,maxRows: 5}" :disabled="isDisabled"
                />
              </FormItem>
            </Row>
          </card>
        </Col>
        <Col span="12" style="margin-left: 2.5%;">
          <card class="card" style="margin-top:15px;">
            <p slot="title">好友印象</p>
            <FormItem
              v-for="(imp, index) in formItem.friends_impression"
              :key="index"
              :label="'好友印象' + ChineseChar[index] + ':'"
            >
              <Col span="18">
                <Input
                  type="textarea"
                  v-model="formItem.friends_impression[index]"
                  placeholder="请输入好友印象"
                  :rows="5"
                  :autosize="{minRows: 5,maxRows: 5}"
                  style="margin-bottom: 11px;" :disabled="isDisabled"
                />
              </Col>
              <Col span="4" offset="1">
                <Button :disabled="isDisabled" @click="handleRemoveImp(index)">删除</Button>
              </Col>
            </FormItem>
            <Row v-if="formItem.friends_impression.length !== 3">
              <FormItem>
                <Col span="12">
                  <Button :disabled="isDisabled" @click="handleAdd" icon="md-add">新增好友印象</Button>
                </Col>
              </FormItem>
            </Row>
            </card>
        </Col>

      </Row>
      <card style="margin-top:15px;">
        <p slot="title">问答环节</p>
        <Row>
          <Col span="11" v-for="(item, index) in formItem.questions_answers" :key="index" :style="index !== 1 ? 'margin-right: 55px;' : ''">
                <FormItem :label="'问题' + ChineseChar[index] + ':'">
                  <Col>
                    <Input
                      type="textarea"
                      v-model="item.Q"
                      :placeholder="'请输入问题' + ChineseChar[index]"
                      :rows="2"
                      :autosize="{minRows: 2,maxRows: 2}" :disabled="isDisabled"
                    />
                  </Col>
                </FormItem>
                <FormItem :label="'回答' + ChineseChar[index] + ':'">
                  <Col>
                    <Input
                      type="textarea"
                      v-model="item.A"
                      :placeholder="'请输入回答' + ChineseChar[index]"
                      :rows="5"
                      :autosize="{minRows: 5,maxRows: 5}" :disabled="isDisabled"
                    />
                  </Col>
                </FormItem>
          </Col>
        </Row>
      </card>
      <card style="margin-top:15px;">
        <p slot="title">隐私信息</p>
        <Row>
          <Col span="5">
            <FormItem label="微信号:">
              <Input :disabled="isDisabled" v-model="formItem.privacy_information.微信号" placeholder="请输入微信号" />
            </FormItem>
          </Col>
          <Col span="4">
            <FormItem label="手机号:">
              <Input :disabled="isDisabled" type="number" class="phone" v-model="formItem.privacy_information.手机号" placeholder="请输入手机号" />
            </FormItem>
          </Col>
          <Col span="4">
            <FormItem label="QQ号:">
              <Input :disabled="isDisabled" v-model="formItem.privacy_information.QQ号" placeholder="请输入QQ号" />
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="年收入:">
              <Input
                type="number"
                number
                v-model="formItem.privacy_information.年收入"
                placeholder="请输入年收入" :disabled="isDisabled"
              >
                <span slot="append">万元</span>
              </Input>
            </FormItem>
          </Col>
          <Col span="4">
            <FormItem label="是否购房:">
              <RadioGroup v-model="formItem.privacy_information.是否购房">
                <Radio label="是" :disabled="isDisabled">是</Radio>
                <Radio label="否" :disabled="isDisabled">否</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="7">
            <FormItem label="其他经济条件:">
              <Input
                type="textarea"
                v-model="formItem.privacy_information.其他经济条件"
                placeholder="请输入其他经济条件"
                :rows="4"
                :autosize="{minRows: 4,maxRows: 4}" :disabled="isDisabled"
              />
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="恋爱经历:">
              <Input
                type="textarea"
                v-model="formItem.privacy_information.恋爱经历"
                placeholder="请输入恋爱经历"
                :rows="4"
                :autosize="{minRows: 4,maxRows: 4}" :disabled="isDisabled"
              />
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="家庭背景:">
              <Input
                type="textarea"
                v-model="formItem.privacy_information.家庭背景"
                placeholder="请输入家庭背景"
                :rows="4"
                :autosize="{minRows: 4,maxRows: 4}" :disabled="isDisabled"
              />
            </FormItem>
          </Col>
        </Row>
      </card>
      <card style="margin-top:15px;">
        <p slot="title">展示</p>
        <FormItem label="是否在平台中展示:" :label-width="120">
          <i-switch :disabled="isDisabled" v-model="formItem.is_show" size="large">
            <span slot="open">是</span>
            <span slot="close">否</span>
          </i-switch>
        </FormItem>
        <Row type="flex" justify="center">
          <FormItem>
            <Button type="primary" size="large" @click="handleSubmit" :disabled="isDisabled">保存</Button>
            <Button size="large" style="margin-left: 8px" @click="handleClose" :disabled="isDisabled">关闭</Button>
          </FormItem>
        </Row>
      </card>
    </Form>
    <Modal v-model="coverUploadModal" width="700" :closable="false" :mask-closable="false">
      <cropper crop-button-text="完成并预览" ref="cover_url" :src="coverimgBase64" @on-crop="onCropCover" />
      <div slot="footer">
        <Button type="primary" size="large" :loading="coverloading" @click="handleCroped">确认裁剪</Button>
        <Button size="large" @click="cancelCover($event)">取消</Button>
      </div>
    </Modal>
    <Modal v-model="imgUploadModal" width="700" :closable="false" :mask-closable="false">
      <cropper crop-button-text="完成并预览" ref="img_cropper" :src="imgBase64" @on-crop="onCropImg" />
      <div slot="footer">
        <Button type="primary" size="large" :loading="imgloading" @click="handleImgCroped">确认裁剪</Button>
        <Button size="large" @click.prevent="cancelCover($event,'img')">取消</Button>
      </div>
    </Modal>
  </section>
</template>
<script>
import regionList from '@/assets/regions.json';
import jobList from '@/assets/job.json';
import schoolList from '@/assets/schools.json';
import cropper from '@/components/cropper';
import format from "@format";
import { downPic } from "@/libs/util";
import * as qiniu from 'qiniu-js'

export default {
  name: 'user_detail',
  data() {
    return {
      formItem: {
        name: "",
        ideal_object: {
          年龄范围: ["",""]
        },
        privacy_information: {
          是否购房: "否"
        },
        friends_impression: [''],
        introduce: [],
        questions_answers: [
          {
            Q: "",
            A: "",
          },
          {
            Q: "",
            A: "",
          },
          {
            Q: "",
            A: "",
          }
				],
				img_list: [],
				cover_img: '',
        is_show: false,
        living_place: []
      },
      ChineseChar: ["一", "二", "三"],
			uploadList: [],
      uploadCoverList: [],
      educationList: [{
        label: '专科',
        value: '专科'
      }, {
        label: '本科',
        value: '本科'
      }, {
        label: '硕士',
        value: '硕士'
      }, {
        label: '博士',
        value: '博士'
      }],
      regionList,
      jobList,
      schoolList,
      searchJobList: [],
      searchSchoolList: [],
      joblLoading: false,
      id: '',
      coverUploadModal: false,
      coverloading: false,
      imgUploadModal: false,
      imgloading: false,
      coverimgBase64: '',
      imgBase64: '',
      isDisabled: false
    };
  },
  components: {
    cropper
  },
  methods: {
    getUserDetail(id) {
      this.$Spin.show({
        render: (h) => {
          return h('div', [
            h('Icon', {
              'class': 'demo-spin-icon-load',
              props: {
                type: 'ios-loading',
                size: 18
              }
            }),
            h('div', '加载中')
          ])
        }
      });
      this.jsonrpc.blind.admin.getCustomerByID(id).then(res=> {
        res.birthday = new Date(res.birthday)
        res.create_date = format(res.create_date, "YYYY-MM-DD hh:mm:ss");
        console.log(res)
        if(res.ideal_object && (!res.ideal_object["年龄范围"])) {
          res.ideal_object["年龄范围"] = ["",""];
        }
        this.formItem = res
        this.$Spin.hide();
      })
      // this.$set(this.formItem);
    },
    handleAdd() {
      this.formItem.friends_impression.push('')
    },
    handleRemoveImp(index) {
      this.formItem.friends_impression.splice(index, 1)
    },
    handleRemove(index) {
      if (this.isDisabled) return
      this.formItem.img_list.splice(index, 1)
    },
    handleCoverRemove() {
      if (this.isDisabled) return
      this.formItem.cover_img = ''
    },
		handleCoverBeforeUpload(file) {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (event) => {
        this.coverimgBase64 = event.srcElement.result
      }

      this.coverUploadModal = true
      return false
      // file.url = file.response.fileURLArr[0]
      // this.formItem.cover_img = file.response.fileURLArr[0]
    },
    handleImgBeforeUpload(file) {

      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (event) => {
        // this.formItem.img_list = [...this.formItem.img_list, event.srcElement.result]
        this.imgUploadModal = true
        this.imgBase64 = event.srcElement.result
      }
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "The file format is incorrect",
        desc:
          "File format of " +
          file.name +
          " is incorrect, please select jpg or png.",
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "Exceeding file size limit",
        desc: "File  " + file.name + " is too large, no more than 2M.",
      });
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        this.searchJobList = this.jobList.filter(item => item.title.indexOf(query) > -1);
        this.loading = false;
      } else {
          this.searchJobList = [];
      }
    },
    searchSchool(query) {
      if (query !== '') {
        this.loading = true
        this.searchSchoolList = this.schoolList.filter(item => item.indexOf(query) > -1);
        this.loading = false;
      } else {
        this.searchSchoolList = [];
      }
    },
    format (labels, selectedData) {
      const index = labels.length - 1;
      return labels[index];
    },
    // 提交
    handleSubmit() {
      let customer = JSON.parse(JSON.stringify(this.formItem));
      customer.create_date = new Date(customer.create_date).getTime();
      customer.birthday = new Date(customer.birthday).getTime();
      customer.is_on_wall = true;
      if (this.id) {
        this.jsonrpc.blind.admin.updateCustomer(Object.assign({
          id: this.id
        }, customer)).then(res=> {
          this.$Message.success('修改成功');
        })
      } else {
        this.jsonrpc.blind.admin.addCustomer(customer).then(res=> {
          this.$Message.success('新增成功');
          this.$router.back()
        })
      }
    },
    handleClose() {
      this.$router.back()
    },
    handleCroped() {
      this.coverloading = true
      this.$refs.cover_url.crop()
      this.coverloading = false
    },
    handleImgCroped() {
      this.imgloading = true
      this.$refs.img_cropper.crop()
      this.imgloading = false
    },
    async onCropCover(blob) {
      this.coverloading = true
      this.formItem.cover_img = await this.uploadImg(blob)
      this.coverloading = false
      this.coverUploadModal = false
    },
    async onCropImg(blob) {
      this.imgloading = true
      let img_list = this.formItem.img_list
      img_list[img_list.length] = await this.uploadImg(blob)
      this.imgloading = false
      this.imgUploadModal = false
    },
    cancelCover(e, cancelType) {
      this.$Modal.confirm({
        title: "确定要取消裁剪吗？",
        content: "刚刚选择的图片需要重新选择",
        onOk: () => {
          if (cancelType) {
            this.imgUploadModal = false
          } else {
            this.formItem.cover_img = ''
            this.coverUploadModal = false
          }
        }
      });
    },
    downPictures() {
      let images = [], { img_list ,avatar } = this.formItem;
      images = images.concat(img_list).concat(avatar)
      images = images.filter(image=> image);
      images.forEach(image=> {
        downPic(image);
      })
    },
    uploadImg(blob) {

      return new Promise((resolve, reject) => {
        this.jsonrpc.blind.admin.getTokenToUpload().then((res, err) => {
          if (err) {
            reject(err)
          } else {
            let observable = qiniu.upload(blob, res.key, res.token, {
              fname: res.key,
              params: {},
              mimeType: null
            }, {
              useCdnDomain: true,
              region: qiniu.region.z0,
              checkByMD5: true
            })
            observable.subscribe({
              next: () => {},
              error: (err) => {
                reject(err)
              },
              complete: (result) => {
                resolve(res.domain + '/' + result.key)
              }
            })
          }
        })
      })
    }
  },
  created() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.getUserDetail(this.id);
    }
    if (this.$route.query.status && this.$route.query.status === "view") {
      this.isDisabled = true
    }
  },
  mounted() {
  },
  watch: {
    $route(newRoute) {
      if (newRoute.name === "user_detail") {
        if (this.$route.query.id) {
          let id = this.$route.query.id;
          this.getUserDetail(id);
        } else {
          this.formItem = {};
        }
      }
    },
  },
};
</script>
<style lang="less" >

.title {
  margin-bottom: 15px;
}

input[type='number']::-webkit-outer-spin-button,
input[type='number']::-webkit-inner-spin-button{
  -webkit-appearance: none !important;
  margin: 0;
}
input[type="number"] {
  -moz-appearance:textfield;
}

.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
.demo-upload-list {
  display: inline-block;
  width: 200px;
  height: 100px;
  text-align: center;
  line-height: 80px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>